<?php
/**
 * Created by PhpStorm.
 * User: renshan
 * Date: 16-6-18
 * Time: 下午10:45
 */

namespace ApiBundle\EventListener;

use ApiBundle\Exception\UserTokenNotFoundException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use ApiBundle\Response\SecurityResponse;

/**
 * Class ApiTokenNotFoundExceptionListener
 * @package ApiBundle\EventListener
 * 监听程序抛出的ApiTokenNotFoundException
 */
class UserTokenNotFoundExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof UserTokenNotFoundException) {
            
            $sec_res = new SecurityResponse();
            $sec_res->setMessage(SecurityResponse::API_TOKEN_NOT_FOUND_MESSAGE);
            $sec_res->setStatus(SecurityResponse::API_TOKEN_NOT_FOUND);

            $response = new Response();


            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
            $response->setContent($sec_res)->headers->replace(['Content-Type'=>'application/json']);
            $event->setResponse($response);
        }

    }
}